﻿Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports System.Net

Public Class OAuth2ClientForm

    Public Shared SCOPE = "public_api"
    Public Shared TOKEN_SERVER_URL = "https://api.alfresco.com/auth/oauth/versions/2/token"
    Public Shared AUTHORIZATION_SERVER_URL = "https://api.alfresco.com/auth/oauth/versions/2/authorize"
    Public Shared ClientIdentifier = "l7xx5b9447a5c6bb498ab29b5d0f4ed2c37a"
    Public Shared ClientSecret = "1ab072f70d494b85a93190457976a483"
    Public Shared Localhost = "http://127.0.0.1:8080/"
    Public Shared CallBackPath = "CallBack"
    Public Shared RedirectUri = Localhost + CallBackPath
    Private authCode = ""

    Private Sub btnGetAccessToken_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetAccessToken.Click
        'Register the authenticator.
        Dim Description = New AuthorizationServerDescription()
        Description.AuthorizationEndpoint = New Uri(AUTHORIZATION_SERVER_URL)
        Description.TokenEndpoint = New Uri(TOKEN_SERVER_URL)
        Description.ProtocolVersion = ProtocolVersion.V20

        Dim consumer = New NativeApplicationClient(Description)
        consumer.ClientIdentifier = ClientIdentifier
        consumer.ClientSecret = ClientSecret

        'Get the auth URL:
        Dim state = New AuthorizationState(New String() {SCOPE})
        state.Callback = New Uri(RedirectUri)
        Dim authUri = consumer.RequestUserAuthorization(state)

        ''Get AuthCode
        'Dim waitForAuthCodeThread = New System.Threading.Thread(AddressOf WaitForAuthCode)
        'waitForAuthCodeThread.Start()

        ''Display WebBrowser control
        'Dim browserForm = New BrowserForm()
        'browserForm.Navigate(authUri)
        'browserForm.ShowDialog()
        ''Request authorization from the user (by opening a browser window):
        ''Process.Start(authUri.ToString())

        'If String.IsNullOrEmpty(authCode) Then
        '    waitForAuthCodeThread.Abort()
        '    listener.Stop()
        '    MessageBox.Show("Authorization failed")
        'Else
        '    'Retrieve the access token by using the authorization code:
        '    Dim authorizationState = CType(consumer.ProcessUserAuthorization(authCode, state), AuthorizationState)
        '    MessageBox.Show("Access token: " + authorizationState.AccessToken)
        'End If

        Dim listener = New HttpListener()
        listener.Prefixes.Add(Localhost)
        listener.Start()

        Dim result = listener.BeginGetContext(New AsyncCallback(AddressOf ListenerCallback), listener)

        'Display WebBrowser control
        Dim browserForm = New BrowserForm()
        browserForm.Navigate(authUri)
        browserForm.ShowDialog()

        If Not result.IsCompleted Then
            listener.Stop()
        End If

        MessageBox.Show("authCode = " + authCode)
        listener.Close()

        ''Retrieve the access token by using the authorization code:
        'Dim authorizationState = CType(consumer.ProcessUserAuthorization(authCode, state), AuthorizationState)
        'MessageBox.Show("Access token: " + authorizationState.AccessToken)

    End Sub

    Private Sub WaitForAuthCode()
        Dim listener = New HttpListener()
        'Add the prefixes. 
        listener.Prefixes.Add(Localhost)
        listener.Start()

        'Note: The GetContext method blocks while waiting for a request. 
        Dim context = listener.GetContext()
        Dim request = context.Request

        authCode = request.QueryString.Item("code")

        'Obtain a response object.
        Dim response = context.Response
        'Construct a response. 
        Dim responseString = "<HTML><BODY> Hello world!</BODY></HTML>"
        Dim buffer = System.Text.Encoding.UTF8.GetBytes(responseString)
        'Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length
        Dim output = response.OutputStream
        output.Write(buffer, 0, buffer.Length)
        'You must close the output stream.
        output.Close()
        listener.Stop()
    End Sub

    Private Sub ListenerCallback(ByVal result As IAsyncResult)
        Dim listener = CType(result.AsyncState, HttpListener)

        If Not listener.IsListening Then
            Return
        End If
        'Call EndGetContext to complete the asynchronous operation.
        Dim context = listener.EndGetContext(result)
        Dim request = context.Request

        authCode = request.QueryString.Item("code")

        'Obtain a response object.
        Dim response = context.Response
        'Construct a response. 
        Dim responseString = "<HTML><BODY> Hello world!</BODY></HTML>"
        Dim buffer = System.Text.Encoding.UTF8.GetBytes(responseString)
        'Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length
        Dim output = response.OutputStream
        output.Write(buffer, 0, buffer.Length)
        'You must close the output stream.
        output.Close()
        listener.Stop()
    End Sub
End Class
